package com.wwj.send.controller;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import com.wwj.common.constant.CommonCodeEnum;
import com.wwj.common.constant.CommonConstant;
import com.wwj.common.entitiy.R;
import com.wwj.common.utils.TokenCheck;
import com.wwj.send.constant.ConstantFinal;
import com.wwj.send.entitiy.SendInformationEntity;
import com.wwj.send.entitiy.UserEntity;
import com.wwj.send.exception.OpenFeignException;
import com.wwj.send.feign.UserFeignService;
import com.wwj.send.service.SendService;
import com.wwj.send.utils.AddressResolutionUtil;
import com.wwj.send.vo.SendVo;
import com.wwj.send.vo.SendVoForMiniVo;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/send")
public class SendController {

    @Resource
    private SendService sendService;

    @Resource
    private UserFeignService userFeignService;

    /**
     * 获取当天寄件数
     * OpenFeign
     */
    @RequestMapping("/getDaySendNumber")
    public R<Integer> getDaySendNumber(){
        int daySendNumber = sendService.selectDaySendNumber();
        System.out.println("============" + daySendNumber + "===============");
        return R.ok(CommonCodeEnum.SUCCESS.getCode(),CommonCodeEnum.SUCCESS.getMsg(),daySendNumber);
    }

    /**
     * 获取寄件数据集
     * http://127.0.0.1:88/api/send/getSendInformation
     */
    @GetMapping("/getSendInformation/{currentPage}/{pageSize}")
    private R<PageInfo<SendInformationEntity>> getSendInformation(@PathVariable("currentPage") String currentPage,
                                                              @PathVariable("pageSize") String pageSize,
                                                              @RequestParam("query") String query){
        PageInfo<SendInformationEntity> pageInfo = sendService.selectSendInformation(currentPage,pageSize,query);
        return R.ok(CommonCodeEnum.SUCCESS.getCode(),CommonCodeEnum.SUCCESS.getMsg(),pageInfo);
    }

    /**
     * 删除单个寄件信息
     *  http://127.0.0.1:88/api/send/removeOne?sendId=3
     */
    @DeleteMapping("/removeOne")
    private R<Object> removeOne(@RequestParam("sendId") String sendId){
        if (sendService.removeById(sendId)){
            return R.ok("删除单个寄件信息成功");
        }else{
            return R.error(CommonCodeEnum.ERROR.getCode(),CommonCodeEnum.ERROR.getMsg());
        }
    }

    /**
     * 批量删除
     *  http://127.0.0.1:88/api/send/batchDelete
     */
    @DeleteMapping("/batchDelete")
    private R<Object> batchDelete(@RequestBody List<SendInformationEntity> sendInformationEntityList) {
        // 抽取ids
        List<String> ids = new ArrayList<>();
        sendInformationEntityList.forEach(item -> {
            ids.add(item.getSendId());
        });
        if(sendService.removeByIds(ids)){
            return R.ok("批量删除成功");
        }else {
            return R.error(CommonCodeEnum.ERROR.getCode(), CommonCodeEnum.ERROR.getMsg());
        }
    }

    /**
     * 新增寄件单
     *  http://127.0.0.1:88/api/send/add
     */
    @PostMapping("/add")
    private R<Object> add(@RequestBody SendVo sendVo) throws ParseException {
        // 查询是否有该用户，没有就返回
        R<UserEntity> userEntityR =  null;
        try {
            userEntityR = userFeignService.getUserById(sendVo.getUserId());
        } catch (OpenFeignException e) {
            e.printStackTrace();
        }
        assert userEntityR != null;
        if (userEntityR.getCode() == CommonCodeEnum.SUCCESS.getCode()) {
            // 用户存在
            // 处理地址信息
            SendInformationEntity sendInformationEntity = new SendInformationEntity();
            BeanUtils.copyProperties(sendVo, sendInformationEntity);
            sendInformationEntity.setSendAddress(sendVo.getSendAddress() + "," + sendVo.getSendAddressDetail());
            // 创建订单时间
            sendInformationEntity.setSendCreateTime(DateUtil.now());
            // 创建姓名
            sendInformationEntity.setSendName(userEntityR.getData().getUserName());
            // 新增
            sendService.save(sendInformationEntity);
            System.out.println("成功======================");
            return R.ok("新增成功");
        }else {
            // 调用失败用户不存在
            return R.error(CommonCodeEnum.USER_NO_EXIST.getCode(),CommonCodeEnum.USER_NO_EXIST.getMsg());
        }
    }

    /**
     * 根据Id获取详细信息
     *  http://127.0.0.1:88/api/send/getDescData?sendId=17
     */
    @GetMapping("/getDescData")
    private R<SendInformationEntity> getDescData(@RequestParam("sendId") String sendId){
        return R.ok(CommonCodeEnum.SUCCESS.getCode(),CommonCodeEnum.SUCCESS.getMsg(),sendService.getById(sendId));
    }

    /**
     * 更新信息
     *  http://127.0.0.1:88/api/send/update
     */
    @PutMapping("/update")
    private R<Object> update(@RequestBody SendVo sendVo){
        // 查询是否有该用户，没有就返回
        R<UserEntity> userEntityR =  null;
        try {
            userEntityR = userFeignService.getUserById(sendVo.getUserId());
        } catch (OpenFeignException e) {
            e.printStackTrace();
        }
        assert userEntityR != null;
        if (userEntityR.getCode() == CommonCodeEnum.SUCCESS.getCode()) {
            // 用户存在
            // 处理地址信息
            SendInformationEntity sendInformationEntity = new SendInformationEntity();
            BeanUtils.copyProperties(sendVo, sendInformationEntity);
            sendInformationEntity.setSendAddress(sendVo.getSendAddress() + "," + sendVo.getSendAddressDetail());
            // 创建订单时间
            sendInformationEntity.setSendCreateTime(DateUtil.now());
            // 创建姓名
            sendInformationEntity.setSendName(userEntityR.getData().getUserName());
            // 新增
            sendService.updateById(sendInformationEntity);
            return R.ok("更新成功");
        }else {
            // 调用失败用户不存在
            return R.error(CommonCodeEnum.USER_NO_EXIST.getCode(),CommonCodeEnum.USER_NO_EXIST.getMsg());
        }
    }

    /**
     * 查询寄件信息表用户是否存在
     * OpenFeign
     */
    @GetMapping("/userExist")
    public R<Object> userExist(@RequestParam("ids") List<String> ids) {
        for (String userId : ids) {
            QueryWrapper<SendInformationEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq(ConstantFinal.FIELD_USER_ID, userId);
            List<SendInformationEntity> list = sendService.list(queryWrapper);
            if (list.size() != 0) {
                return R.error(CommonCodeEnum.USER_EXIST.getCode(), CommonCodeEnum.USER_EXIST.getMsg());
            }
        }
        return R.ok("可以删除该用户");
    }

    /**
     * 微信小程序获取用户寄件单
     *  http://192.168.0.115:88/api/send/getExpressData
     */
    @GetMapping("/getExpressData")
    private R<Object> getExpressData(HttpServletRequest request,@RequestParam("query") String query){
        String token = request.getHeader(CommonConstant.REQUEST_HEADER_TOKEN);
        // 解析该token的用户id
        String userId = TokenCheck.getUserIdByToken(token);
        // 查询
        QueryWrapper<SendInformationEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(ConstantFinal.FIELD_USER_ID, userId);
        if (!query.isEmpty()){
            queryWrapper.and(wrapper -> wrapper.like(ConstantFinal.FIELD_SEND_TO_NAME, query).or()
                    .like(ConstantFinal.FIELD_SEND_ADDRESS,query).or()
                    .like(ConstantFinal.FIELD_SEND_TO_MOBILE, query).or()
                    .like(ConstantFinal.FIELD_SEND_CONTENT, query).or()
                    .like(ConstantFinal.FIELD_SEND_ID, query));
        }
        // 降序排列
        queryWrapper.orderByDesc(ConstantFinal.FIELD_SEND_CREATE_TIME);
        List<SendInformationEntity> list = sendService.list(queryWrapper);
        return R.ok(CommonCodeEnum.SUCCESS.getCode(), CommonCodeEnum.SUCCESS.getMsg(), list);
    }

    /**
     * 微信小程序提交寄件单
     * http://192.168.0.115:88/api/send/addSendForUser
     */
    @PostMapping("/addSendForUser")
    private R<Object> addSendForUser(HttpServletRequest request,@RequestBody SendVoForMiniVo sendVoForMiniVo){
        String token = request.getHeader(CommonConstant.REQUEST_HEADER_TOKEN);
        // 解析该token的用户id
        String userId = TokenCheck.getUserIdByToken(token);
        // 设置sendStatus sendPay
        SendInformationEntity sendInformationEntity = new SendInformationEntity();
        BeanUtils.copyProperties(sendVoForMiniVo, sendInformationEntity);
        sendInformationEntity.setSendStatus(ConstantFinal.VALUE_SEND_STATUS_NO_SEND);
        sendInformationEntity.setSendPay(ConstantFinal.VALUE_SEND_NO_PAY);
        // 分割重组地址选项
        String address = "";
        List<Map<String, String>> list = AddressResolutionUtil.addressResolution(sendVoForMiniVo.getSendProvince());
        for (Map<String, String> map : list) {
            String province = map.get("province");
            String city = map.get("city");
            String county = map.get("county");
            address = province + "/" + city + "/" + county + ",";
        }
        // 拼接详细地址
        address = address + sendVoForMiniVo.getSendDescription();
        sendInformationEntity.setSendAddress(address);
        // 设置创建时间
        sendInformationEntity.setUserId(userId);
        sendInformationEntity.setSendCreateTime(DateUtil.now());
        // 新增
        sendService.save(sendInformationEntity);
        return R.ok("新增寄件单成功");
    }

    /**
     * 微信小程序根据id删除寄件单
     *  http://192.168.0.115:88/api/send/deleteSendByUser?sendId=28
     */
    @DeleteMapping("/deleteSendByUser")
    private R<Object> deleteSendByUser(@RequestParam("sendId") String sendId){
        boolean flag = sendService.removeById(sendId);
        if (flag){
            return R.ok("删除成功");
        }else {
            return R.error("删除失败");
        }
    }




}
